package com.zhida.smartcontrol.common;

import android.os.Bundle;
import android.os.Environment;
import android.view.View;

import com.jay.tools.base.BaseDialogFragment;
import com.jay.tools.configure.Party;
import com.jay.tools.utils.EventBusUtils;
import com.jay.tools.utils.LogUtil;
import com.qw.photo.CoCo;
import com.qw.photo.callback.GetImageCallBack;
import com.qw.photo.constant.CompressStrategy;
import com.qw.photo.dispose.ImageDisposer;
import com.qw.photo.pojo.TakeResult;

import java.io.File;
import java.io.IOException;

/**
 * author: tanjianpei
 * date: 2019/12/17 017 11:43
 * description: 拍照
 */
public class PhotoDialogFragment extends BaseDialogFragment {

    public static PhotoDialogFragment newInstance() {
        Bundle args = new Bundle();
        PhotoDialogFragment fragment = new PhotoDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected Object getLayout() {
        return new View(mActivity);
    }

    @Override
    protected void initDatas(Bundle savedInstanceState) {
        File file = createSDCardFile();
        if (null == file) {
            dismiss();
            return;
        }
        CoCo.with(this)
                .take(file)
                .applyWithDispose(new ImageDisposer().degree(60).strategy(CompressStrategy.QUALITY))
                .start(new GetImageCallBack<TakeResult>() {
                    @Override
                    public void onDisposeStart() {

                    }

                    @Override
                    public void onSuccess(TakeResult takeResult) {
                        File file = takeResult.getTargetFile();
                        if (file == null) {
                            dismiss();
                            return;
                        }
                        String path = file.getAbsolutePath();
                        LogUtil.e(TAG, "路径：" + path);
                        EventBusUtils.post(new PhotoOkEvent(path));
                        dismiss();
                    }

                    @Override
                    public void onFailed(Exception e) {
                        e.printStackTrace();
                        dismiss();
                    }

                    @Override
                    public void onCancel() {
                        dismiss();
                    }
                });
    }

    private File createSDCardFile() {
        String dir = Party.getApplicationContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES) + File.separator;
        String path = dir + 1 + ".jpg";
        try {
            File file = new File(path);
            if (!file.exists())
                file.createNewFile();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

}
